package com.service.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * java分页插件
 * @author run
 * @date 2022/08/20
 */
public class PageUtils<T> {

    private Integer current = 1;
    private Integer size = 10;

    /**
     * 开始分页
     * @param current 当前页
     * @param size    每页记录数
     * @return {@link PageUtils}<{@link T}>
     */
    public PageUtils<T> startPage(Integer current,Integer size) {
        this.current = current;
        this.size = size;
        return this;
    }

    /**
     * java实现分页效果 用于无法使用分页插件的情况
     * @param list    列表
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public synchronized Map<String,Object> doSelectPage(List<T> list){

        if (list != null && list.size() > 0) {
            int total = list.size();
            int pages = 0;
            if (total % size == 0){
                pages = total/size;
            }else {
                pages = total/size + 1;
            }
            if (current > pages) {
                return encapsulationPageMap(0,0,0,0,null);
            }
            int currentPage = current - 1;
            int start = currentPage * size;
            int end = start + size;
            if (pages == current && total % size != 0) {
                end = start + total % size;
            }
            List<T> records = list.subList(start, end);
            return encapsulationPageMap(current, size, total, pages, records);
        }
        return encapsulationPageMap(current,size,0,0,list);
    }


    /**
     * 封装分页返回结果
     * @param current 当前页
     * @param size    每页记录数
     * @param total   总共数量
     * @param pages   页面
     * @param records 列表
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    private Map<String, Object> encapsulationPageMap(Integer current, Integer size, int total, int pages, List<T> records) {
        Map<String, Object> map = new HashMap<>();
        map.put("size", size);
        map.put("total", total);
        map.put("current", current);
        map.put("pages", pages);
        map.put("records", records);
        return map;
    }



}
